import logging
import os
from datetime import datetime
from typing import Optional


class ProcessLogger:
    """进程管理专用日志记录器"""

    def __init__(self, log_file: str = "logs/process_manager.log"):
        self.log_file = log_file
        self._setup_logger()

    def _setup_logger(self):
        """设置日志记录器"""
        # 确保日志目录存在
        os.makedirs(os.path.dirname(self.log_file), exist_ok=True)

        # 创建专用的logger
        self.logger = logging.getLogger('process_manager')
        self.logger.setLevel(logging.INFO)

        # 避免重复添加handler
        if not self.logger.handlers:
            # 文件handler
            file_handler = logging.FileHandler(self.log_file, encoding='utf-8')
            file_handler.setLevel(logging.INFO)

            # 格式化器
            formatter = logging.Formatter(
                '[%(asctime)s] [%(levelname)s] %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            file_handler.setFormatter(formatter)

            self.logger.addHandler(file_handler)

    def log_process_start_attempt(self, process_name: str, display_name: str):
        """记录进程启动尝试"""
        self.logger.info(f"尝试启动进程: {process_name} ({display_name})")

    def log_process_start_success(self, process_name: str, pid: int, resources: list):
        """记录进程启动成功"""
        resource_str = self._format_resources(resources)
        self.logger.info(f"进程启动成功: {process_name} [PID: {pid}] [资源: {resource_str}]")

    def log_process_start_failed(self, process_name: str, reason: str):
        """记录进程启动失败"""
        self.logger.warning(f"进程启动失败: {process_name} - {reason}")

    def log_process_stop_attempt(self, process_name: str):
        """记录进程停止尝试"""
        self.logger.info(f"尝试停止进程: {process_name}")

    def log_process_stop_success(self, process_name: str, method: str = "graceful"):
        """记录进程停止成功"""
        method_desc = {
            "graceful": "优雅退出",
            "graceful_interrupt": "优雅退出(SIGINT)",  # 添加这行
            "graceful_term": "优雅退出(SIGTERM)",  # 添加这行
            "forced": "强制终止",
            "already_dead": "进程已结束"  # 添加这行
        }.get(method, f"正常停止({method})")  # 显示原始method

        self.logger.info(f"进程停止成功: {process_name} ({method_desc})")

    def log_process_stop_failed(self, process_name: str, reason: str):
        """记录进程停止失败"""
        self.logger.warning(f"进程停止失败: {process_name} - {reason}")

    def log_resource_conflict(self, process_name: str, conflicts: str):
        """记录资源冲突"""
        self.logger.warning(f"资源冲突: {process_name} - {conflicts}")

    def log_system_reset(self, stopped_processes: list):
        """记录系统重置"""
        if stopped_processes:
            processes_str = ", ".join(stopped_processes)
            self.logger.info(f"系统重置完成，已停止进程: {processes_str}")
        else:
            self.logger.info("系统重置完成，无运行中的进程")

    def log_health_check(self, unhealthy_processes: list):
        """记录健康检查结果"""
        if unhealthy_processes:
            processes_str = ", ".join(unhealthy_processes)
            self.logger.warning(f"健康检查发现异常进程: {processes_str}")
        else:
            self.logger.info("健康检查完成，所有进程正常")

    def log_config_loaded(self, process_count: int):
        """记录配置加载"""
        self.logger.info(f"配置加载成功，注册了 {process_count} 个进程")

    def log_system_startup(self):
        """记录系统启动"""
        self.logger.info("进程管理系统启动")

    def log_api_request(self, endpoint: str, process_name: Optional[str] = None):
        """记录API请求"""
        if process_name:
            self.logger.info(f"API请求: {endpoint} - 进程: {process_name}")
        else:
            self.logger.info(f"API请求: {endpoint}")

    def _format_resources(self, resources: list) -> str:
        """格式化资源向量为可读字符串"""
        resource_names = ["motor", "lidar", "camera_read", "camera_write"]
        used_resources = []

        for i, usage in enumerate(resources):
            if usage > 0:
                used_resources.append(f"{resource_names[i]}:{usage}")

        return ", ".join(used_resources) if used_resources else "无"


# 全局日志实例
process_logger = ProcessLogger()